package com.stack.admin.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.stack.admin.mapper.AdNewsMapper;
import com.stack.admin.service.AdNewsService;
import com.stack.apis.article.IArticleClient;
import com.stack.apis.wemedia.IWemediaClient;
import com.stack.common.utils.thread.AdminThreadLocalUtil;
import com.stack.model.admin.dtos.AdNewsDto;
import com.stack.model.admin.dtos.PageQueryDto;
import com.stack.model.admin.pojos.AdNews;
import com.stack.model.admin.pojos.AdUser;
import com.stack.model.article.dtos.ArticleDto;
import com.stack.model.common.dtos.PageResponseResult;
import com.stack.model.common.dtos.ResponseResult;
import com.stack.model.common.enums.AppHttpCodeEnum;
import com.stack.model.wemedia.pojos.WmChannel;
import com.stack.model.wemedia.pojos.WmNews;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

/**
 * @author 112
 * @description 针对表【ad_news(媒体审核内容信息表)】的数据库操作Service实现
 * @createDate 2023-11-16 00:09:26
 */
@Service
@Slf4j
public class AdNewsServiceImpl extends ServiceImpl<AdNewsMapper, AdNews> implements AdNewsService {

    @Resource
    private IWemediaClient wemediaClient;

//    @Resource
    @Qualifier("com.stack.apis.article.IArticleClient")
    @Autowired
    private IArticleClient articleClient;

    @Resource
    private AdNewsMapper adNewsMapper;



    /**
     * 查看文章列表
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult getNewsList(PageQueryDto dto) {

//        WmNewsPageReqDto wmNewsPageReqDto = new WmNewsPageReqDto();
////        wmNewsPageReqDto.setStatus(dto.getStatus());
//        wmNewsPageReqDto.setKeyword(dto.getTitle());
//        wmNewsPageReqDto.setSize(dto.getSize());
//        wmNewsPageReqDto.setPage(dto.getPage());
//
//        //3.结果返回
//        ResponseResult wemediaNewsList = wemediaClient.getNewsList(wmNewsPageReqDto);
//        ResponseResult responseResult = new PageResponseResult(dto.getPage(), dto.getSize(), (int) 11);
//        responseResult.setData(wemediaNewsList.getData());
//        return wemediaNewsList;

        LambdaQueryWrapper<AdNews> queryWrapper = Wrappers.lambdaQuery();
        queryWrapper.eq(ObjectUtils.isNotEmpty(dto.getStatus()), AdNews::getStatus, dto.getStatus());
        queryWrapper.like(ObjectUtils.isNotEmpty(dto.getTitle()), AdNews::getTitle, dto.getTitle());
        queryWrapper.orderByDesc(AdNews::getPublishTime);

        IPage<AdNews> page = new Page<>(dto.getPage(), dto.getSize());
        IPage<AdNews> pageList = adNewsMapper.selectPage(page, queryWrapper);
        log.info("数量：{}", pageList.getTotal());
        List<AdNewsDto> newsDtoList = JSON.parseArray(JSON.toJSONString(pageList.getRecords()), AdNewsDto.class);

        //3.结果返回
        ResponseResult responseResult = new PageResponseResult(dto.getPage(), dto.getSize(), (int) pageList.getTotal());
        responseResult.setData(pageList.getRecords());
        return responseResult;
    }

    /**
     * 文章审核通过
     *
     * @param dto
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResponseResult authPass(AdNewsDto dto) {
        if (dto.getId() == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }

        AdUser adUser = AdminThreadLocalUtil.getUser();
        if (adUser == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }

        //更新审核状态
        LambdaUpdateWrapper<AdNews> updateWrapper = Wrappers.lambdaUpdate();
        updateWrapper.eq(AdNews::getId, dto.getId());
        updateWrapper.set(AdNews::getStatus, 9);
        updateWrapper.set(AdNews::getReason, "已发布");
//        updateWrapper.set(AdNews::getStatus, 4);
//        updateWrapper.set(AdNews::getReason, "审核成功");
        adNewsMapper.update(null, updateWrapper);

        //审核成功保存app端的相关的文章数据
        AdNews adNews = adNewsMapper.selectById(dto.getId());

//        wemediaClient.saveApArticleAndWmNews(new NewsIdVO(dto.getId()));

        WmNews wmNews = new WmNews();

        //保存app文章
        if (adNews.getArticleId() == null) {
            ResponseResult responseResult = saveAppArticle(adNews);
            if (!responseResult.getCode().equals(200)) {
                throw new RuntimeException("WmNewsAutoScanServiceImpl-文章审核，保存app端相关文章数据失败");
            }

            //admin回填article_id
            adNews.setArticleId((Long) responseResult.getData());
            updateById(adNews);

            //wemedia回填article_id
            wmNews.setArticleId((Long) responseResult.getData());

        }

        //修改wemedia文章状态
//        BeanUtils.copyProperties(adNews, wmNews);
        wmNews.setId(adNews.getId());
        wmNews.setStatus((short) 9);
        wmNews.setReason("已发布");
        wemediaClient.updateNewsById(wmNews);

        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    /**
     * 保存app端相关的文章数据
     *
     * @param adNews
     */
    private ResponseResult saveAppArticle(AdNews adNews) {

        log.info("adNews:{}", adNews);

        ArticleDto dto = new ArticleDto();
        //属性的拷贝
        BeanUtils.copyProperties(adNews, dto);

        //频道
        WmChannel wmChannel = wemediaClient.getChannelBase(adNews.getChannelId());
        if (wmChannel != null) {
            dto.setChannelName(wmChannel.getName());
        }

        //作者
        dto.setAuthorId(adNews.getUserId().longValue());
        log.info("adNews:{}", adNews);
        dto.setAuthorName(adNews.getAuthorName());

        //文章的布局
        dto.setLayout(adNews.getType().shortValue());

        //设置文章id
        if (adNews.getArticleId() != null) {
            dto.setId(adNews.getArticleId());
        }
        dto.setCreatedTime(new Date());

        log.info("保存文章dto:{}", JSON.toJSONString(dto));
        ResponseResult responseResult = articleClient.saveArticle(dto);
        return responseResult;
    }


    /**
     * 文章审核失败
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult authFail(AdNewsDto dto) {
        if (dto.getId() == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }

        AdUser adUser = AdminThreadLocalUtil.getUser();
        if (adUser == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }

        LambdaUpdateWrapper<AdNews> updateWrapper = Wrappers.lambdaUpdate();
        updateWrapper.eq(AdNews::getId, dto.getId())
                .set(AdNews::getStatus, 2);
        adNewsMapper.update(null, updateWrapper);

        //同步wemedia文章状态
        WmNews wmNews = new WmNews();
        wmNews.setId(dto.getId());
        wmNews.setStatus((short) 2);
        wmNews.setReason("审核失败");
        wemediaClient.updateNewsById(wmNews);

        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    /**
     * 获取文章详情
     *
     * @param id
     * @return
     */
    @Override
    public ResponseResult getNewsOne(Long id) {

        AdUser adUser = AdminThreadLocalUtil.getUser();
        if (adUser == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }

        AdNews adNews = adNewsMapper.selectById(id);

        ResponseResult responseResult = new ResponseResult();
        responseResult.setData(adNews);

        return responseResult;
    }

    /**
     * 保存admin审核文章
     *
     * @param dto
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResponseResult saveAdCheckNews(AdNewsDto dto) {

//        try {
//            Thread.sleep(3000);
//        } catch (InterruptedException e) {
//            e.printStackTrace();
//        }
        //1.检查参数
        if (dto == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }

        log.info("保存admin审核文章:{}", dto);
        //保存文章
        AdNews adNews = new AdNews();
        BeanUtils.copyProperties(dto, adNews);
//        AdNews adNews = JSON.parseObject(JSON.toJSONString(dto), AdNews.class);
        //封面图片  list---> string
        if (dto.getImages() != null) {
            //[1dddfsd.jpg,sdlfjldk.jpg]-->   1dddfsd.jpg,sdlfjldk.jpg
            String imageStr = StringUtils.join(dto.getImages(), ",");
            adNews.setImages(imageStr);
        }

        log.info("插入的新闻:{}", adNews);
        adNewsMapper.insert(adNews);

        //3.结果返回  文章的id
        ResponseResult responseResult = new ResponseResult();
        responseResult.setData(adNews.getId());
        responseResult.setErrorMessage(AppHttpCodeEnum.SUCCESS.getErrorMessage());

        return responseResult;
    }
}




